<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="场馆" prop="stadiumId">
        <el-select v-model="queryParams.stadiumId" placeholder="请选择场馆" clearable>
          <el-option
            v-for="dict in dict.type.puyu_stadium"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班次" prop="classesId">
        <el-select v-model="queryParams.classesId" placeholder="请选择班次" clearable>
          <el-option
            v-for="dict in dict.type.puyu_classes"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="教练" prop="coachId">
        <el-select v-model="queryParams.coachId" placeholder="请选择教练" clearable>
          <el-option
            v-for="coach in coachList"
            :key="coach.coachId"
            :label="coach.coachName"
            :value="coach.coachId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['puyu:lesson:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['puyu:lesson:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['puyu:lesson:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['puyu:lesson:export']"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <span>总学员{{studentTotal}}人</span>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="lessonList" @selection-change="handleSelectionChange" show-summary sum-text="总学员人数" :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="场馆" align="center" prop="stadiumId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.puyu_stadium" :value="scope.row.stadiumId"/>
        </template>
      </el-table-column>
      <el-table-column label="班次" align="center" prop="classesId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.puyu_classes" :value="scope.row.classesId"/>
        </template>
      </el-table-column>
      <el-table-column label="教练" align="left" prop="coachId">
        <template slot-scope="scope">
          <span>{{ getCoachName(scope.row.coachId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学员数量" align="center" prop="studentNum">
        <template slot-scope="scope">
          <!-- <span style="color: red;font-weight: bolder;"> -->{{ scope.row.puyuLessonStudents.length }}<!-- </span> -->
        </template>
      </el-table-column>
      <el-table-column label="学员姓名" align="center" prop="studentNames">
        <template slot-scope="scope">
          <span>{{getStudentNames(scope.row.puyuLessonStudents)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="checkEditLesson(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddStudent(scope.row)"
            v-hasPermi="['puyu:lesson:rollcall']"
          >点名</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['puyu:lesson:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课时对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="教练" prop="coachId">
          <el-select
            v-model="form.coachId"
            placeholder="请选择教练"
            :disabled="isDisabled"
            :clearable="isClearAble"
          >
            <el-option
              v-for="coach in coachList"
              :key="coach.coachId"
              :label="coach.coachName"
              :value="coach.coachId"
              @click.native="handleCoachChange(coach)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="场馆" prop="stadiumId">
          <el-select v-model="form.stadiumId" placeholder="请选择场馆">
            <el-option
              v-for="dict in dict.type.puyu_stadium"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班次" prop="classesId">
          <el-select v-model="form.classesId" placeholder="请选择班次">
            <el-option
              v-for="dict in dict.type.puyu_classes"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLesson, getLesson, delLesson, addLesson, updateLesson } from "@/api/puyu/lesson";
import { listCoachs, listAllCoachs } from "@/api/puyu/coach";
import { parseTime } from "@/utils/ruoyi";
var defaultDate = parseTime(new Date(), '{y}-{m}-{d}')
export default {
  name: "Lesson",
  dicts: ['sys_del_flag', 'puyu_classes', 'puyu_stadium'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 所有学员总人次
      allStudentTotal: 0,
      // 当前分页学员总人次
      studentTotal: 0,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 课时表格数据
      lessonList: [],
      // 未删除教练数据
      coachList: undefined,
      // 所有教练数据
      coachAllList: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isDisabled: false,
      isClearAble: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        coachId: null,
        stadiumId: null,
        classesId: null,
        createTime: defaultDate,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getCoachList();
  },
  methods: {
    /** 计算两个时间差几小时 */
    hoursBetween(time1, time2) {
      // 将时间字符串转换为Date对象
        const date1 = new Date(time1);
        const date2 = new Date(time2);
        // 计算两个时间的时间戳差值
        const diff = Math.abs(date2.getTime() - date1.getTime());
        // 将差值转换为小时
        const hours = diff / (1000 * 60 * 60);
        // 返回结果
        return hours;
    },
    /** 校验是否显示修改按钮 */
    checkEditLesson(item) {
      if (this.$auth.hasRole("manager")) {
        return true;
      }
      let hours = this.hoursBetween(parseTime(item.createTime, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'));
      return this.$auth.hasPermi("puyu:lesson:edit") &&  hours <= 3 ;
    },
    /** 查询课时列表 */
    getList() {
      this.loading = true;
      listLesson(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.lessonList = response.rows;
        this.studentTotal = this.getStudentTotal(this.lessonList);
        if (response.extTotal >= 0) {
          this.allStudentTotal = response.extTotal;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询教练用户列表 */
    getCoachList(coachType = '') {
      if (!coachType) {
        listAllCoachs().then(response => {
          this.coachList = response.data;
          this.coachAllList = response.data;
        });
      } else {
        listCoachs().then(response => {
          this.coachList = response.data;
        });
      }
    },
    handleCoachChange(coach) {
      this.form.userId = coach.userId;
      this.form.deptId = coach.deptId;
    },
    /** 根据coachId获取教练姓名 */
    getCoachName(coachId) {
      if (this.coachAllList) {
        return this.coachAllList.filter(item => item.coachId == coachId)[0].coachName;
      }
      return '';
    },
    /** 拼接学员姓名 */
    getStudentNames(puyuLessonStudents) {
      if (puyuLessonStudents.length == 0) {
        return '';
      }
      let names = '';
      for(let i = 0; i < puyuLessonStudents.length; i++) {
        if (i === 0) {
          names = puyuLessonStudents[i].studentName;
        } else {
          names = names + ',' + puyuLessonStudents[i].studentName;
        }
      }
      return names;
    },
    /** 根据coachId获取教练姓名 */
    getStudentTotal(list) {
      if (list.length == 0) {
        return 0;
      }
      let total = 0;
      for(let i = 0; i < list.length; i++) {
        total = total + list[i].puyuLessonStudents.length;
      }
      return total;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '总学员人数';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // 只对studentNum这一列进行总计核算。
        if (column.property === 'studentNum') {
          sums[index] = '当前分页 ' + this.studentTotal + ' 人次；共 ' + this.allStudentTotal + ' 人次';
        }
      });
      return sums;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lessonId: null,
        userId: null,
        deptId: null,
        coachId: null,
        stadiumId: null,
        classesId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lessonId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isClearAble = true;
      this.isDisabled = false;
      this.getCoachList('1')
      this.title = "添加课时";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isClearAble = false;
      this.isDisabled = true;
      this.getCoachList()
      const lessonId = row.lessonId || this.ids
      getLesson(lessonId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课时";
      });
    },
    // 点名
    handleAddStudent(row) {
      const lessonId = row.lessonId;
      this.$router.push("/puyu/lesson-student/lesson/" + lessonId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lessonId != null) {
            updateLesson(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLesson(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lessonIds = row.lessonId || this.ids;
      this.$modal.confirm('是否确认删除课时编号为"' + lessonIds + '"的数据项？').then(function() {
        return delLesson(lessonIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('puyu/lesson/export', {
        ...this.queryParams
      }, `lesson_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
